package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.entity.SupplierPage;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierDao supplierDao;

    @Override
    public Map<String, Object> getSupplierList(SupplierPage supplierPage) {

        //优先处理分页数据
        Integer page = supplierPage.getPage();
        Integer rows = supplierPage.getRows();
        //重新定义从第几条开始
        supplierPage.setPage((page - 1) * rows);

        //定义返回的集合
        Map<String,Object> map = new HashMap<>();

        //获取返回的数据列表
        List<Supplier> supplierList = supplierDao.getSupplierList(supplierPage);

        //获取返回的总条数
        Integer supplierListTotal = supplierDao.getSupplierListTotal();

        //将数据放入map 并返回数据
        map.put("total",supplierListTotal);
        map.put("rows",supplierList);

        return map;
    }

    @Override
    public int save(Supplier supplier) {
        int save = supplierDao.save(supplier);
        return save;
    }

    @Override
    public Supplier getSupplierId(String supplierId) {
        Supplier supplier = supplierDao.getSupplierId(supplierId);
        return supplier;
    }

    @Override
    public int updateById(Supplier supplier) {
        return supplierDao.updateById(supplier);
    }



    @Override
    public int saveOrUpdate(Supplier supplier) {
        if(StringUtils.isEmpty(supplier.getSupplierId())){
           return save(supplier);
        }
        return updateById(supplier);
    }

    //删除
    @Override
    public int deleteById(String supplierId) {
        return supplierDao.deleteById(supplierId);
    }


    //批量删除
    @Override
    public void deleteByIds(String[] ids) {
        List<String> idsList = Arrays.stream(ids).collect(Collectors.toList());
        for (String supplierId : idsList){
            this.deleteById(supplierId);
        }
    }
}
